package cn.sanch.pet.service.impl;

import cn.sanch.pet.domain.PetType;
import cn.sanch.pet.mapper.PetTypeMapper;
import cn.sanch.pet.service.IPetTypeService;
import cn.sanch.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    /**
     * 获取宠物类型级联树
     * @return
     */
    @Override
    public List<PetType> typrTree() {
        Map<Long, PetType> map = new HashMap<>();
        // 查询所有类型
        List<PetType> petTypes = petTypeMapper.findAll();
        // 遍历存入map
        for (PetType petType : petTypes) {
            // key值为当前对象的id， value为当前对象
            map.put(petType.getId(), petType);
        }

        List<PetType> typeTree = new ArrayList<>();
        for (PetType petType : petTypes) {
            //表示没有父id，自己就是最高级
            if (petType.getPid() == null) {
                typeTree.add(petType);
                // 否则就表示有父对象
            }else {
                // 找到父对象的id
                Long pid = petType.getPid();
                //
                PetType parentType = map.get(pid);

                // 将当前对象设置到父对象的子集合里
                parentType.getChildren().add(petType);
            }
        }

        return typeTree;
    }
}
